#include <iostream>
#include <string>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <cstring>

// 实现一个简单的求和程序,将用户输入两个数字进行求和
// 子进程读取用户的输入 , 父进程进行计算，并将结果输出

void Write(int wfd)
{
    while(true)
    { 
        std::string buffer;
        getline(std::cin , buffer);

        // 向管道中写入数据
        write(wfd , buffer.c_str() , buffer.size());
    }
}

int Get_value(char* buffer , int n , int* x , int* y)
{
    int flag = 0 , index = 0;
    while(index < n )
    {
        char ch = buffer[index];
        if(isspace(ch))
        {
            index ++;
            continue;
        }
        if(!isdigit(ch)) return -1;
       
        // 该位置是数字进行读取
        int tmp = 0;
        while(isdigit(buffer[index])) tmp = tmp*10 + buffer[index++] - '0';
        if(flag == 0 ) *x = tmp;
        else *y = tmp;
        flag++;
    }
    return flag == 2 ? 0 : -1;
}


void Read(int rfd)
{
    while(true)
    {

        char buffer[1024];
        int n = read(rfd , buffer , sizeof(buffer));
        buffer[n] = 0;
        // 读取buffer中的数字
        int x  , y;
        int flag = Get_value(buffer , n , &x , &y);

        std::cout << " get a task " << buffer << std::endl;
        if(flag == -1) std::cout << " err import" << std::endl;
        else std::cout << " answer is :" << x + y << std::endl;
    }

}



int main()
{
    int fd[2];
    int n = pipe(fd);
    if(n < 0) return 1;

    pid_t id = fork();
    if(id == 0)
    {
        close(fd[0]);       // 让子进程负责写
        Write(fd[1]);
        exit(0);
    }
    
    close(fd[1]);           // 父进程负责读 
    Read(fd[0]);
    return 0;
}

